package guoanmaker.provider.business.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import guoanmaker.provider.business.model.OperatorCity;
import guoanmaker.provider.business.model.ProvideCity;
import guoanmaker.provider.business.model.ProvideCommodity;
import guoanmaker.provider.business.model.ProvideCommodityServiceRange;
import guoanmaker.provider.business.model.ProvideRoom;
import guoanmaker.provider.business.model.ProviderBusiness;
import guoanmaker.provider.business.repository.OperatorCityRepository;
import guoanmaker.provider.business.repository.OperatorServerClassRepository;
import guoanmaker.provider.business.repository.ProvideCityRepository;
import guoanmaker.provider.business.repository.ProvideCommodityRepository;
import guoanmaker.provider.business.repository.ProvideCommodityServiceRangeRepository;
import guoanmaker.provider.business.repository.ProvideRoomRepository;
import guoanmaker.provider.business.repository.ProviderBusinessRepository;

@Service
public class ProvideCommodityService implements ProvideCommodityServiceInterface{

	@Autowired
	private ProvideCommodityRepository commodityRepository;
	
	@Autowired
	private ProvideCommodityServiceRangeRepository serviceRangeRepository;
	
	@Autowired
	private ProviderBusinessRepository businessReposity;
	
	@Autowired
	private OperatorServerClassRepository provideServerClassRepository;
	
	@Autowired
	private ProvideRoomRepository roomRepository;
	
	@Autowired
	private OperatorServerClassService classService;
	
	@Autowired
	private OperatorCityRepository operatorCityRepository;
		
	@Autowired
	private ProvideCityRepository provideCityRepository;
	
	@PersistenceContext
	private EntityManager manager;

	
	/**
	 *添加商品
	 *@param commodity(商品实体) 
	 * */
	@Override
	public Integer addProvideCommodity(ProvideCommodity commodity) {
		Integer result=200;
		try {
			if(commodity!=null){
				commodity.setClickRate(0);
				String serverType=commodity.getServiceType().getId();//获取商品类型
				String businessId=commodity.getProviderBusiness().getId();//商户id
				ProviderBusiness business=businessReposity.findOne(businessId);
				if(business==null){
					return 250;
				}
				String comditys=business.getCommoditys();//商家经营范围
				List<String> userList = null;
				if(comditys.contains(",")){//判断商家是否有多项经营范围
					userList = Arrays.asList(comditys.split(","));
				}else{
					userList = new ArrayList<>();
					userList.add(comditys);
				}
				List<String> serverTypeIds=null;
				boolean bool=false;
				for(int i=0;i<userList.size();i++){
					serverTypeIds=classService.getServerIdByParentServerId(userList.get(i));
					if(serverTypeIds.contains(serverType)){
						bool=true;
						break;
					}
				}
				if(bool){//如果经营范围有商品类型，执行此逻辑
					List<ProvideCommodityServiceRange> serviceRanges=null;
					if(commodity!=null){
						String type=commodity.getType();//商品所属大类1:空间 2:其他 3:培训
						if(type.equals("1")){
							String roomId=commodity.getRomm().getId();//空间id
							ProvideRoom room=roomRepository.findByIdIsAndRoomStateIs(roomId,2);
							if(room==null){
								return 350;
							}
						}
						if(commodity.getSalesVolume()==null){//判断销量是否为null
							commodity.setSalesVolume(0);
						}
						if(commodity.getEvaluateValue()==null){//判断商品评价数量
							commodity.setEvaluateValue(0);
						}
						 serviceRanges=commodity.getServiceRange();
						 commodity.setServiceRange(null);
						 commodity.setOrderforms(null);
						 commodity.setReleaseTime(new Date());
						 commodity.setReadState(1);
						 commodity=commodityRepository.save(commodity);
						 String isTerritoryRestriction=commodity.getIsTerritoryRestriction();//是否有地域限制 1:有 2:没有
						 if(type.equals("2") && isTerritoryRestriction.equals("1")){
							 if(serviceRanges!=null){
								 	for(int i=0;i<serviceRanges.size();i++ ){
								 		ProvideCommodityServiceRange serviceRange=serviceRanges.get(i);
								 		if(serviceRange.getArea()!=null && serviceRange.getArea().getId()==null){
								 			serviceRange.setArea(null);
								 		}
								 		if(serviceRange.getCity()!=null && serviceRange.getCity().getId()==null){
								 			serviceRange.setCity(null);
								 		}
								 		if(serviceRange.getProvince()!=null && serviceRange.getProvince().getClass()==null){
								 			serviceRange.setProvince(null);
								 		}
								 		serviceRange.setCommodity(commodity);
								 		serviceRangeRepository.save(serviceRange);
								 	}
							 }
						 }
					}
				}else{
					result=300;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result=250;
		}
		return result;
	}

	/**
	 *通过主键修改商品
	 *@param commodity(商品实体) 
	 *@return result 200:正确 250:失败 300:没有经营范围 350:没有空间
	 * */
	@Override
	public Integer updateProvideCommodity(ProvideCommodity commodity) {
		Integer result=200;
		try {
			if(commodity!=null){
				String serverType=commodity.getServiceType().getId();//获取商品类型
				String businessId=commodity.getProviderBusiness().getId();//商户id
				ProviderBusiness business=businessReposity.findOne(businessId);
				if(business==null){
					return 250;
				}
				String comditys=business.getCommoditys();//商家经营范围
				List<String> userList = null;
				if(comditys.contains(",")){//判断商家是否有多项经营范围
					userList = Arrays.asList(comditys.split(","));
				}else{
					userList = new ArrayList<>();
					userList.add(comditys);
				}
				List<String> serverTypeIds=null;
				boolean bool=false;
				for(int i=0;i<userList.size();i++){
					serverTypeIds=classService.getServerIdByParentServerId(userList.get(i));
					if(serverTypeIds.contains(serverType)){
						bool=true;
						break;
					}
				}
				if(bool){//如果经营范围有商品类型，执行此逻辑
					List<ProvideCommodityServiceRange> serviceRanges=null;
					if(commodity!=null){
						String type=commodity.getType();//商品所属大类1:空间 2:其他 3:培训
						if(type.equals("1")){
							String roomId=commodity.getRomm().getId();//空间id
							ProvideRoom room=roomRepository.findByIdIsAndRoomStateIs(roomId,2);
							if(room==null){
								return 350;
							}
						}
						if(commodity.getSalesVolume()==null){//判断销量是否为null
							commodity.setSalesVolume(0);
						}
						if(commodity.getEvaluateValue()==null){//判断商品评价数量
							commodity.setEvaluateValue(0);
						}
						if(commodity.getClickRate()==null){
							commodity.setClickRate(0);
						}
						 serviceRanges=commodity.getServiceRange();
						 commodity.setServiceRange(null);
						 commodity.setOrderforms(null);
						 commodity.setReleaseTime(new Date());
						 commodity.setReadState(1);
						 commodity=commodityRepository.save(commodity);
						 String isTerritoryRestriction=commodity.getIsTerritoryRestriction();//是否有地域限制 1:有 2:没有
						 if(type.equals("2") && isTerritoryRestriction.equals("1")){
							 if(serviceRanges!=null){
								 	for(int i=0;i<serviceRanges.size();i++ ){
								 		ProvideCommodityServiceRange serviceRange=serviceRanges.get(i);
								 		if(serviceRange.getArea()!=null && serviceRange.getArea().getId()==null){
								 			serviceRange.setArea(null);
								 		}
								 		if(serviceRange.getCity()!=null && serviceRange.getCity().getId()==null){
								 			serviceRange.setCity(null);
								 		}
								 		if(serviceRange.getProvince()!=null && serviceRange.getProvince().getClass()==null){
								 			serviceRange.setProvince(null);
								 		}
								 		serviceRange.setCommodity(commodity);
								 		serviceRangeRepository.save(serviceRange);
								 	}
							 }
						 }
					}
				}else{
					result=300;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result=250;
		}
		return result;
	}

	/**
	 * 通过商品状态查询商品列表
	 * @param commodityState 商品状态
	 * @return 
	 * */
	@Override
	public List<ProvideCommodity> selectByCommdityState(Integer commodityState) {
		List<ProvideCommodity> commoditys=commodityRepository.findByCommodityState(commodityState);
		List<ProvideCommodity> lists=new ArrayList<ProvideCommodity>();
		for(ProvideCommodity commodity: commoditys){
			commodity.getProviderBusiness().setProvideCommodity(null);
			lists.add(commodity);
			if(commodity.getServiceRange()!=null){
				List<ProvideCommodityServiceRange> serviceRange=commodity.getServiceRange();
				for(int i=0;i<serviceRange.size();i++){
					serviceRange.get(i).setCommodity(null);
				}
				commodity.setServiceRange(serviceRange);
			}
		}
		return lists;
	}

	/**
	 * 根据动态查询条件分页查询数据
	 * @param commodity 
	 * @param page 当前页
	 * @param size 每页条数
	 * @return 商品结果集
	 * */
	@Override
	@Transactional
	public  Map<String, Object> selectByCommditys (Integer page, Integer size,Integer commodityState,String businessID,String commodityName,String service_type_id) {
		commodityName=commodityName==null?"":commodityName;
		String jql="select new guoanmaker.provider.business.modelnobind.ProvideCommodityMove("
				+ "t.id,t.commodityName,t.finalPrice,t.stock,t.salesVolume,t.releaseTime,t.auditOpinion,t.commodity_smallimage,sv.serverName,t.commodityCode,t.reasoncontent) "
				+ "from ProvideCommodity t left join t.providerBusiness b left join t.serviceType sv "
				+ " where  b.id=:businessId and t.commodityName like :name  ";
		if(StringUtils.isNotEmpty(service_type_id)){
			List<String> ids=classService.getServerIdByParentServerId(service_type_id);//查询二级列表下面的子项
			String str=getServiceType(ids);
			jql=jql+" and sv.id in ("+str+") ";
		}
		if(commodityState==4){
			jql=jql+" and  t.commodityState in (4,7) ";
		}else{
			jql=jql+" and  t.commodityState in ("+commodityState+") ";
		}
		Query query=manager.createQuery(jql);//查询商品列表
		query.setParameter("businessId", businessID);
		//query.setParameter("commodityState", commodityState);
		query.setParameter("name", "%"+commodityName+"%");
		query.setMaxResults(size);
		query.setFirstResult(page*size);
		List<ProvideCommodity> lists=query.getResultList();
		Query query2=manager.createQuery(jql);//查询商品列表
		query2.setParameter("businessId", businessID);
		query2.setParameter("name", "%"+commodityName+"%");
		List<ProvideCommodity> countList=query2.getResultList();
		Map<String, Object> reMap=new HashMap<>();
		reMap.put("commoditys", lists);
		reMap.put("total",countList.size());
		if(commodityState==3 || commodityState==5){
			String updatesql="UPDATE ProvideCommodity p set p.readState=1 where p.commodityState=:commodityState and p.readState=2 and p.providerBusiness.id=:businessId";
			Query query4=manager.createQuery(updatesql);//查询商品列表
			query4.setParameter("businessId", businessID);
			query4.setParameter("commodityState", commodityState);
			int result=query4.executeUpdate();
			System.out.println(result);
		}
		
		String jpql="select new guoanmaker.provider.business.modelnobind.ProvideCommodityRead(c.commodityState,count(c.id)) "
				+ "from ProvideCommodity c left join c.providerBusiness b  where  b.id=:businessId and c.readState=2 and  c.commodityState in (3,5) GROUP BY c.commodityState";
		Query query3=manager.createQuery(jpql);//按照状态统计未阅读数据
		query3.setParameter("businessId", businessID);
		List<ProvideCommodity> readList=query3.getResultList();
		reMap.put("readList", readList);
		return reMap;
	}

	/**
	 * 删除商品
	 * @param id(商品表主键)
	 * */
	@Override
	@Transactional
	public void deleteCommdity(String id) {
		String jpql = "UPDATE ProvideCommodity p set p.commodityState=6 where p.id =:id"; 
		Query query = manager.createQuery(jpql); 
		query.setParameter("id",id); 
		query.executeUpdate();
		
		ProvideCommodity provideCommodity=commodityRepository.findOne(id);
		String servercity="";
		String servercity1="";
		if(provideCommodity.getProviderBusiness()!=null){
			//isTerritoryRestriction;//是否有地域限制 1:有 2:没有
			if(provideCommodity.getIsTerritoryRestriction()!=null){
					 List<ProvideCommodity>  comms=commodityRepository.selectByCommodity(provideCommodity.getProviderBusiness().getId());
						 for (ProvideCommodity provideCommodity2 : comms) {
							if(provideCommodity2.getIsTerritoryRestriction()!=null){
								if(provideCommodity2.getIsTerritoryRestriction().equals("2")){
	    	     					 List<OperatorCity> ops=	operatorCityRepository.findAll();
	    	     					 if(ops.size()>0){
	    	     						 for (OperatorCity operatorCity : ops) {
	    	     							 ProvideCity  provideCity1=provideCityRepository.findByCode(operatorCity.getCityId());
	    	     							 if(provideCity1!=null){
	    	     								 servercity1+=provideCity1.getName()+",";
	    	     							 }
	    	     						 }
	    	     					 }
								}else if(provideCommodity2.getIsTerritoryRestriction().equals("1")){
									List<ProvideCommodityServiceRange>  pcs=serviceRangeRepository.selectByServerArea(provideCommodity.getId());
	    	     					 if(pcs.size()>0){
	    	     						 for (ProvideCommodityServiceRange provideCommodityServiceRange : pcs) {
	    	     							 ProvideCity  city=	 provideCityRepository.findOne(provideCommodityServiceRange.getCity().getId());
	    	     							 servercity+=city.getName()+",";
										}
	    	     					 }
								}
								
							}
					}
				
			}
			String c=removeSameString(servercity);
			String c1=removeSameString(servercity1);
			String c2="";
			if(!c1.equals("")){
				c2=c1;
			}else{
				c2=c;
			}
			ProviderBusiness providerBusiness=businessReposity.findOne(provideCommodity.getProviderBusiness().getId());
			if(providerBusiness!=null){
				providerBusiness.setServiceAreas(c2);
				businessReposity.save(providerBusiness);
			}
		}
	}

	/**
	 * 通过主键id获取商品信息
	 * @param id(商品表主键)
	 * @return 商品对象
	 * */
	@Override
	public ProvideCommodity selectById(String id) {
		
		ProvideCommodity commodity=commodityRepository.findOne(id);
		if(commodity!=null){
			if(commodity.getProviderBusiness()!=null){
				commodity.getProviderBusiness().setProvideCommodity(null);
				commodity.getProviderBusiness().setPersonalUser(null);
			}
			if(commodity.getServiceRange()!=null){
				List<ProvideCommodityServiceRange> serviceRange=commodity.getServiceRange();
				if(serviceRange.size()>0){
					for(int i=0;i<serviceRange.size();i++){
						serviceRange.get(i).setCommodity(null);
					}
				}
				commodity.setServiceRange(serviceRange);
			}
			if(commodity.getRomm()!=null){
				commodity.getRomm().setSpaceReserves(null);
				commodity.getRomm().setBusiness(null);
			}
			commodity.setOrderforms(null);
		}
		return commodity;
	}

	//测试组合查询
	@Override
	public Map<String, Object> selectByCommditys(Pageable pageable,ProvideCommodity commodity) {
		//Page<ProvideCommodity> commoditys=commodityRepository.findBybusiness_idIsAndCommodityNameIs(commodity.getProviderBusiness().getId(), commodity.getCommodityName(), pageable);
		Page<ProvideCommodity> commoditys=null;
		List<ProvideCommodity> lists=null;
		if(commoditys.getContent()!=null){
			lists=new ArrayList<ProvideCommodity>();
			for(ProvideCommodity commo: commoditys){
				commo.getProviderBusiness().setProvideCommodity(null);
				commo.setServiceRange(null);
				lists.add(commo);
			}
		}
		Map<String, Object> reMap=new HashMap<>();
		reMap.put("commoditys", lists);
		reMap.put("total", commoditys.getTotalElements());
		return reMap;
	}

	/***
	 * @deprecated 批量删除商品
	 */
	@Override
	@Transactional
	public void deleteCommditys(String ids) {
		if( ids!=null){
			String hql = "UPDATE ProvideCommodity p set p.commodityState=6 where  "; 
			if(ids.contains(",")){
				String[] id=ids.split(",");
				String zhi="";
				for(int i=0;i<id.length;i++){
					if(i==0){
						zhi=" id='"+id[i]+"' ";
					}else{
						zhi=zhi+"or id='"+id[i]+"' ";
					}
				}
				hql=hql+zhi;
			}else{
				hql=hql+" id='"+ids+"' ";
			}
			Query query=manager.createQuery(hql);
			int result=query.executeUpdate();
			System.out.println(result);
		}
		
	}

	
	/***
	* @Title: updateCommditysStock 
	* @Description: 修改商品库存
	* @param  id
	* @param  stock
	* @param  设定文件 
	* @return boolean    返回类型 
	* @throws 
	 */
	@Override
	@Transactional
	public boolean updateCommditysStock(String id, Integer stock) {
		boolean bool=true;
		try {
			String hql="update ProvideCommodity set stock="+stock+" where id=:id";
			Query query=manager.createQuery(hql);
			query.setParameter("id", id);
			int result=query.executeUpdate();
			System.out.println(result);
		} catch (Exception e) {
			bool=false;
		}
		return bool;
	}

	
	/**
	* @Title: updateCommditysState 
	* @Description: 商户修改商品状态
	* @param  id
	* @param  state
	* @param @return    设定文件 
	* @return boolean    返回类型 
	* @throws 
	 */
	@Override
	@Transactional
	public boolean updateCommditysState(String ids, Integer state) {
		boolean bool=true;
		try {
			if( ids!=null){
				String hql="update ProvideCommodity set commodityState="+state+" where ";
				if(ids.contains(",")){
					String[] id=ids.split(",");
					String zhi="";
					for(int i=0;i<id.length;i++){
						if(i==0){
							zhi=" id='"+id[i]+"' ";
						}else{
							zhi=zhi+"or id='"+id[i]+"' ";
						}
					}
					hql=hql+zhi;
				}else{
					hql=hql+" id='"+ids+"' ";
				}
				Query query=manager.createQuery(hql);
				int result=query.executeUpdate();
			}
		} catch (Exception e) {
			bool=false;
		}
		return bool;
	}


	/**
	 * 获取服务类型id串
	 * @author baixsh
	 * @param  ids(类型主键集合)
	 * */
	public static String getServiceType(List<String> ids){
		String str="";
		if(ids!=null){
			for(int k=0;k<ids.size();k++){
				if(k==0){
					str=str+"'"+ids.get(k)+"'";
				}else{
					str=str+",'"+ids.get(k)+"'";
				}
			}
		}
		return str;
	}

	//修改
	@Override
	@Transactional
	public Integer updateCommditysShelvesState(String id, Integer state) {
		ProvideCommodity commodity=commodityRepository.findOne(id);
		Integer result=200;
		try {
			if(commodity!=null){
				String serverType=commodity.getServiceType().getId();//获取商品类型
				String comditys=commodity.getProviderBusiness().getCommoditys();//商家经营范围
				List<String> userList = null;
				if(comditys.contains(",")){//判断商家是否有多项经营范围
					userList = Arrays.asList(comditys.split(","));
				}else{
					userList = new ArrayList<>();
					userList.add(comditys);
				}
				List<String> serverTypeIds=null;
				boolean bool=false;
				for(int i=0;i<userList.size();i++){
					serverTypeIds=classService.getServerIdByParentServerId(userList.get(i));
					if(serverTypeIds.contains(serverType)){
						bool=true;
						break;
					}
				}
				if(bool){//如果经营范围有商品类型，执行此逻辑
					String hql="update ProvideCommodity set commodityState="+state+" where "+" id='"+id+"' ";
					Query query=manager.createQuery(hql);
					query.executeUpdate();
				}else{
					result=300;
				}
			}
		} catch (Exception e) {
			result=250;
		}
		return result;
	}
	
	/** 
	 * 去掉重复字符串 
	 * @param str 
	 * @return String  
	 * */  
	public static  String removeSameString(String str){    
	    Set<String> mLinkedSet = new LinkedHashSet<String>();    
	    String[] strArray = str.split(",");    
	    StringBuffer sb = new StringBuffer();    
	    for (int i = 0; i < strArray.length; i++)    
	    {    
	        if (!mLinkedSet.contains(strArray[i]))    
	        {    
	            mLinkedSet.add(strArray[i]);    
	            sb.append(strArray[i] + " ");    
	        }else{  
	  //          System.out.println("重复字符:"+strArray[i]);  
	        }    
	    }    
//	    System.out.println(mLinkedSet);    
	    return sb.toString().substring(0, sb.toString().length() - 1);    
	}    
}
